package org.jetlinks.pro.things.impl.connector;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.hswebframework.web.bean.FastBeanCopier;
import org.jetlinks.pro.things.ProviderProperties;
import org.jetlinks.pro.things.ThingsConnector;
import org.jetlinks.pro.things.ThingsConnectorProvider;
import org.jetlinks.pro.things.ThingsManagerContext;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;

@AllArgsConstructor
@Component
public class CompositeThingsConnectorProvider implements ThingsConnectorProvider {

    private final ThingsManagerContext context;

    @Override
    public String getId() {
        return "composite";
    }

    @Override
    public String getName() {
        return "组合连接器";
    }

    @Override
    public Mono<ThingsConnector> createConnector(Map<String, Object> configuration) {
        CompositeThingsConnectorProperties properties = FastBeanCopier.copy(configuration, new CompositeThingsConnectorProperties());
        properties.validate();

        return Flux
            .fromIterable(properties.connectors)
            .concatMap(prop -> context.createConnector(prop.getProvider(), prop.getConfiguration()))
            .collectList()
            .map(CompositeThingsConnector::new);
    }

    @Getter
    @Setter
    public static class CompositeThingsConnectorProperties {
        private List<ProviderProperties> connectors;

        public void validate() {
            Assert.notEmpty(connectors, "connectors can not be empty");
            connectors.forEach(ProviderProperties::validate);
        }
    }
}
